package com.atguigu.spzx.manger.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.utils.AuthContextUtil;
import io.swagger.v3.core.util.Json;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 请求到controller之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //kinif4j请求路径
        String servletPath = request.getServletPath();
        System.out.println(servletPath);

        //获取请求方式
        String method = request.getMethod();
        //如果是预检请求options
        if (method.equalsIgnoreCase("OPTIONS")) {
            return true;
        }
        //获取token
        String token = request.getHeader("token");
        //判断
        if (StrUtil.isEmpty(token)) {
            //设置响应内容
            responseNoLoginInfo(response);
            return false;
        }

        //从redis中获取数据
        String strUser = redisTemplate.opsForValue().get("user:login:" + token);
        //判断
        if (StrUtil.isEmpty(strUser)) {
            //设置响应内容
            responseNoLoginInfo(response);
            return false;
        }

        //转换数据
        SysUser sysUser = JSON.parseObject(strUser, SysUser.class);
        //存储到线程变量中
        AuthContextUtil.set(sysUser);
        //重新设置redis中toke的时间
        redisTemplate.expire("user:login:" + token, 60, TimeUnit.MINUTES);


        return true;

    }

    /**
     * 构建响应信息
     *
     * @param response
     */
    private void responseNoLoginInfo(HttpServletResponse response) {

        //构建响应内容
        Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        //处理中文乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");

        //获取响应流
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            //响应
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }


    }


    /**
     * 响应之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除线程中的本地变量
        AuthContextUtil.remove();

    }
}
